package com.mega.fe.util.klass;

import com.mega.fe.util.MEGA;
import com.mega.fe.util.UnsafeUtil;
import net.minecraft.client.main.Main;
import org.lwjgl.glfw.GLFW;

import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.lang.invoke.VarHandle;
import java.util.jar.JarFile;

public class PathSetter {
    public static void init() throws Throwable {
        Instrumentation instrumentation = McInstGetter.i();
        System.out.println(instrumentation);
        appendPathTOSystem(instrumentation, Main.class.getResource("").getPath());
        appendPathTOSystem(instrumentation, net.minecraft.server.Main.class.getResource("").getPath());
        appendToClassPathForInstrumentation("com/mega/fe/util/klass/EventUtil");

        KlassCreator.addClass(GLFW.class.getClassLoader(), EventUtil.class);
        System.out.println("Wwfwsef::::"+GLFW.class.getClassLoader());
    }

    public static void appendPathTOSystem(Instrumentation instrumentation, String path) throws IOException {
        if (path == null) return;
        instrumentation.appendToSystemClassLoaderSearch(new JarFile(path.substring(5, path.lastIndexOf(".jar"))+".jar"));
    }

    public static void appendToClassPathForInstrumentation(String path) throws Throwable{
        Class<?> loaderClass = MEGA.DefineClassLoader.APP_LOADER.getClass();
        MethodHandle methodHandle = MEGA.IMPL_LOOKUP().findVirtual(loaderClass, "appendToClassPathForInstrumentation", MethodType.methodType(void.class, String.class));
        methodHandle.bindTo(MEGA.DefineClassLoader.APP_LOADER).invoke(path);
    }

}
